package timing.ukulele.storage.config;

import io.minio.MinioClient;
import okhttp3.HttpUrl;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import timing.ukulele.storage.minio.StorageClientFactory;

import java.net.URL;

@Configuration
@EnableConfigurationProperties(StorageClientProperties.class)
public class StorageClientAutoConfiguration {
    private final StorageClientProperties storageClientProperties;

    public StorageClientAutoConfiguration(StorageClientProperties storageClientProperties) {
        this.storageClientProperties = storageClientProperties;
    }

    @Bean
    MinioClient minioClient() throws Exception {
        URL url = null;
        if (storageClientProperties.getUrlString() != null && storageClientProperties.getUrlString().length() > 0) {
            url = new URL(storageClientProperties.getUrlString());
        }
        HttpUrl httpUrl = null;
        if (storageClientProperties.getHttpUrlString() != null && storageClientProperties.getHttpUrlString().length() > 0) {
            httpUrl = HttpUrl.parse(storageClientProperties.getHttpUrlString());
        }
        return StorageClientFactory.INSTANCE.createStorageClient(storageClientProperties.getEndpoint(),
                storageClientProperties.getPort(),
                storageClientProperties.getAccessKey(),
                storageClientProperties.getSecretKey(),
                storageClientProperties.getSecure(),
                url, httpUrl);
    }
}
